<?php

/*
	info: 系统总控制静态类
	$Id: lfly.class.php 13 2011-03-25 08:33:49Z lfly1573@gmail.com $
*/

if (!defined('WEB_IN'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

class Lfly
{
	public static $callback = NULL;	//回调函数
	public static $user = array();	//用户信息
	public static $webCache = array();	//缓存数据
	public static $webConfig = array();	//配置数据
	public static $webCookie = array();	//cookie数据
	public static $webGlobal = array();	//全局数据
	public static $webLang = array();	//语言包数据
	public static $webModel = array();	//载入模型数据
	public static $webRequest = array();	//参数获取数据
	public static $webServer = array();	//服务器相关数据
	public static $webUpfile = array();	//文件上传数据
	
	/**
	 * 系统初始化
	 * @return void
	 */
	public static function Init()
	{
		self::LoadConfig();
		self::InitializeVar();
		self::SetServer();
		self::SetRequest();
		self::InitializeUser();
		self::LoadWebSetting();
		if (!empty(self::$callback) && function_exists(self::$callback))
		{
			call_user_func(self::$callback);
		}
		self::Run();
	}

	/**
	 * 检查当前模块控制器方法合法性
	 * @return void
	 */
	public static function CheckMode()
	{
		if (!defined('WEB_CHECKED_MODE'))
		{
			define('WEB_CHECKED_MODE', TRUE);
			if (!preg_match("/^[a-z0-9]+$/i", self::$webGlobal['module']) || !preg_match("/^".self::$webGlobal['module']."_Ctl_[a-z0-9]+$/i", self::$webGlobal['controller']) || !preg_match('/^[a-z0-9]+$/i', self::$webGlobal['method']) || !isset(self::$webCache['webMethod'][self::$webGlobal['controller'].'_'.self::$webGlobal['method']]) || self::$webCache['webMethod'][self::$webGlobal['controller'].'_'.self::$webGlobal['method']]['portal']!=self::$portal)
			{
				header("HTTP/1.0 404 Not Found");
				exit();
			}
			self::$webGlobal['modulenum'] = isset(self::$webCache['webModule'][self::$webGlobal['module']]) ? self::$webCache['webModule'][self::$webGlobal['module']] : 0;
			self::$webGlobal['methodnum'] = self::$webCache['webMethod'][self::$webGlobal['controller'].'_'.self::$webGlobal['method']]['id'];
			self::$webGlobal['methodlimit'] = isset(self::$webCache['webMethod'][self::$webGlobal['controller'].'_'.self::$webGlobal['method']]['limit']) ? self::$webCache['webMethod'][self::$webGlobal['controller'].'_'.self::$webGlobal['method']]['limit'] : 0;
		}
	}

	/**
	 * 格式化URL地址
	 * @param $strController 控制器名称
	 * @param $strMethod 方法
	 * @param $mixParam 其他参数，可以为数组(如: array('a'=>1, 'b'=>2) )或字符串(如: a=1&b=2)
	 * @return string url地址
	 */
	public static function FormatURL($strController = '', $strMethod = '', $mixParam = '')
	{
		if ($strController == '')
		{
			$strController = self::$webGlobal['controller'];
		}
		if ($strMethod == '')
		{
			$strMethod = self::$webGlobal['method'];
		}
		if ($strController=='' || $strMethod=='')
		{
			return WEB_PATH.'/';
		}

		if (is_array($mixParam))
		{
			$tempStrParam = '';
			foreach ($mixParam as $tempKey => $tempValue)
			{
				$tempStrParam .= '&'.$tempKey.'='.urlencode($tempValue);
			}
			$mixParam = $tempStrParam;
		}
		elseif ($mixParam != '')
		{
			$mixParam = '&'.$mixParam;
		}

		$returnUrl = WEB_PATH.'/';
		if (isset(self::$webCache['webMethod'][$strController.'_'.$strMethod]))
		{
			$strPortal = self::$webCache['webMethod'][$strController.'_'.$strMethod]['portal'];
			$strUrlParam = str_replace('_Ctl_', '&c=', $strController).'&m='.$strMethod.$mixParam;
			$returnUrl = WEB_PATH.$strPortal.((defined('WEB_HTMLFILE') && WEB_HTMLFILE) ? 'index.php' : '').'?'.$strUrlParam;
			if ($strPortal!='/'.WEB_ADMIN.'/' && isset(self::$webRequest['adminmode']) && self::$webRequest['adminmode']==1 && String::CheckHaveVar(self::$webGlobal['frontAdminUserInfo']['adminPurview'], '163') && !isset(self::$webRequest['adminonepage']))
			{
				$returnUrl .= '&adminmode=1';
			}
			elseif (defined('WEB_REWRITE') && WEB_REWRITE && $strPortal!='/'.WEB_ADMIN.'/' && !strpos($returnUrl, '&adminmode=1') && !strpos($returnUrl, '&notrewrite=1'))
			{
				include WEB_ROOT.'/urlrewrite.inc.php';
			}
		}

		return $returnUrl;
	}

	/**
	 * 载入语言文件
	 * @param $strFile 语言文件名称(如: “abc”对应的默认文件为“abc_zh.lang.php”)
	 * @param $strModule 模块(为空时表示在系统目录查找语言文件)
	 * @return void
	 */
	public static function LoadLanguage($strFile, $strModule = '')
	{
		$strFile = strtolower($strFile);
		$strModule = strtolower($strModule);
		$webLang = array();
		$tempFile = WEB_ROOT.(($strModule=='') ? '/library/lang/' : "/module/{$strModule}/lang/").$strFile.'_'.WEB_LANG.'.lang.php';
		if (is_file($tempFile))
		{
			include_once $tempFile;
		}
		if (!empty($webLang))
		{
			self::$webLang += $webLang;
		}
	}

	/**
	 * 载入模型
	 * @param $strModel 模型名称
	 * @param $bolLoadSet 是否载入模块设置
	 * @return object 模型对象的引用地址
	 */
	public static function &LoadModel($strModel, $bolLoadSet = TRUE)
	{
		if (!isset(self::$webModel[$strModel]))
		{
			if ($bolLoadSet)
			{
				$tempLinePos = strpos($strModel, '_');
				if ($tempLinePos!==FALSE && $tempLinePos>0)
				{
					self::LoadModuleSetting(substr($strModel, 0, $tempLinePos));
				}
			}
			self::$webModel[$strModel] = new $strModel();
		}
		return self::$webModel[$strModel];
	}

	/**
	 * 载入模块配置
	 * @param $strModule 模块名称
	 * @return void
	 */
	public static function LoadModuleSetting($strModule)
	{
		$tempDefine = 'WEB_MODULE_'.strtoupper($strModule);
		if (!defined($tempDefine))
		{
			define($tempDefine, TRUE);
			$strFilePath = WEB_ROOT.'/module/'.strtolower($strModule);
			$tempInit = (@include $strFilePath.'/init.inc.php');
			if ($tempInit !== FALSE)
			{
				if (isset($isHaveConstantFile) && $isHaveConstantFile)
				{
					include_once $strFilePath.'/constant.inc.php';
				}
				if (isset($isHaveLanguageFile) && $isHaveLanguageFile)
				{
					self::LoadLanguage('default', $strModule);
				}
			}
			Cache::LoadCacheSet($strModule);
		}
	}

	/**
	 * 翻译语言标记
	 * @param $strLang 语言字符格式为“[lang:]语言标记[@@参数1@@参数2...]”
	 * @return string 格式化后的字符串
	 */
	public static function TranslateLanguage($strLang)
	{
		$tempLang = preg_replace("/^lang:/i", "", $strLang);
		$tempArray = explode('@@', $tempLang);
		if (!isset(self::$webLang[$tempArray[0]]))
		{
			$tempReturn = $strLang;
		}
		elseif (!isset($tempArray[1]))
		{
			$tempReturn = self::$webLang[$tempArray[0]];
		}
		else
		{
			$tempArray[0] = self::$webLang[$tempArray[0]];
			$tempReturn = call_user_func_array('sprintf', $tempArray);
		}
		return $tempReturn;
	}

	/* 通用前台入口判断数据 */
	public static function WebCommonInit()
	{
		Lfly::CheckMode();
		Cache::LoadCacheSet('Ad');
		Cache::LoadCacheSet('Class');
		Cache::LoadCacheData('class');

		/* 判断主站小站方法可用情况 */
		if (Lfly::$webGlobal['methodlimit']>0 && ((defined('WEB_SITE_ID') && WEB_SITE_ID>0 && Lfly::$webGlobal['methodlimit']!=2) || ((!defined('WEB_SITE_ID') || WEB_SITE_ID<=0) && Lfly::$webGlobal['methodlimit']!=1)))
		{
			header("HTTP/1.1 403 Forbidden");
			exit();
		}

		/* 联盟cookie处理 */
		if (!isset(Lfly::$webCookie['meid']) && isset(Lfly::$webCookie['uniondata']))
		{
			$tempUnionClearCookie = TRUE;
			$tempUnionArray = explode("\t", Encryption::Decrypt(Lfly::$webCookie['uniondata'], md5(WEB_UNION_KEY.$_SERVER['HTTP_USER_AGENT'])));
			if (count($tempUnionArray) == 4)
			{
				$tempUnsid = intval($tempUnionArray[0]);
				$tempUnaid = intval($tempUnionArray[1]);
				$tempUnsidSubid = intval($tempUnionArray[2]);
				$tempUnionCheckTime = intval($tempUnionArray[3]);
				if ($tempUnsid>0 && ($tempUnaid>0 || $tempUnsidSubid>0) && abs(WEB_TIME-$tempUnionCheckTime)<43200)
				{
					$tempUnionClearCookie = FALSE;
					Lfly::$webCookie['unsid'] = $tempUnsid;
					Lfly::$webCookie['unaid'] = $tempUnaid;
					Lfly::$webCookie['unsidsubid'] = $tempUnsidSubid;
				}
			}
			if ($tempUnionClearCookie)
			{
				Network::ClearCookie('uniondata');
			}
		}

		/* 可视化处理 */
		if (isset(Lfly::$webRequest['adminmode']) && Lfly::$webRequest['adminmode']==1)
		{
			$objAdminUserInfo =& Lfly::LoadModel('User_Mdl_AdminUserInfo');
			Lfly::$webGlobal['frontAdminUserInfo'] = $objAdminUserInfo->CheckUser();
			if (empty(Lfly::$webGlobal['frontAdminUserInfo']) || (Lfly::$webGlobal['frontAdminUserInfo']['adminIsSystem']!=1 && !String::CheckHaveVar(Lfly::$webGlobal['frontAdminUserInfo']['adminPurview'], '57')))
			{
				Lfly::$webRequest['adminmode'] = 0;
			}
			!defined('WEB_NOT_COUNT') and define('WEB_NOT_COUNT', TRUE);
		}
	}

	/*******************************************************************/

	/* 初始化用户信息 */
	private static function InitializeUser()
	{
		self::$user['uid'] = 0;
		self::$user['ip'] = Network::GetIp();
		self::$user['ipnum'] = Network::IpToNum(self::$user['ip']);

		/* 用户唯一编码分配 */
		if (!isset(self::$webCookie['olcode']) || !preg_match('/^[a-z0-9]{6}$/i', self::$webCookie['olcode']))
		{
			self::$webCookie['olcode'] = String::Random(6);
			$tempOlCodeTime = TimeDate::ConvTime(TimeDate::FormatTime(WEB_TIME, 'FD').' 23:59:59')-WEB_TIME;
			if ($tempOlCodeTime > 0)
			{
				Network::SetCookieNew('olcode', self::$webCookie['olcode'], $tempOlCodeTime, TRUE);
			}
		}
		self::$user['olcode'] = self::$webCookie['olcode'];
	}

	/* 初始化系统变量 */
	private static function InitializeVar()
	{
		self::$webGlobal['module'] = self::$webGlobal['controller'] = self::$webGlobal['method'] = NULL;
		self::$webGlobal['modulenum'] = self::$webGlobal['methodnum'] = 0;
		self::$webGlobal['htmlTitle'] = self::$webGlobal['htmlDescription'] = '';
		self::$webGlobal['htmlKeyword'] = self::$webGlobal['htmlHead'] = self::$webGlobal['htmlNavigation'] = array();
		self::$webGlobal['page'] = array();
	}

	/* 载入系统参数配置 */
	private static function LoadConfig()
	{
		require WEB_ROOT.'/config.inc.php';
		self::$webConfig = $webConfig;
	}

	/* 载入网站设置 */
	private static function LoadWebSetting()
	{
		self::LoadLanguage('system');
		Cache::LoadCacheSet('Admin');
		Cache::LoadCacheData('webmode');
	}

	/* 分配控制器执行 */
	private static function Run()
	{
		self::CheckMode();
		self::LoadModuleSetting(self::$webGlobal['module']);
		$controller = self::$webGlobal['controller'];
		$method = self::$webGlobal['method'];
		$objController = new $controller();
		if (!method_exists($objController, $method))
		{
			exit("Can not load method: {$controller}->{$method}().");
		}
		$objController->$method();
	}

	/* 获取参数处理 */
	private static function SetRequest()
	{
		foreach ($_GET as $tempKey => $tempValue)
		{
			self::$webRequest[$tempKey] = String::AddSlashesNew($tempValue);
		}
		foreach ($_POST as $tempKey => $tempValue)
		{
			self::$webRequest[$tempKey] = String::AddSlashesNew($tempValue);
		}

		if (!empty(self::$webServer['getstr']))
		{
			$tempAmpPos = strpos(self::$webServer['getstr'], '&');
			if ($tempAmpPos !== FALSE)
			{
				self::$webGlobal['module'] = String::AddSlashesNew(trim(urldecode(substr(self::$webServer['getstr'], 0, $tempAmpPos))), TRUE);
			}
			elseif (strpos(self::$webServer['getstr'], '=') === FALSE)
			{
				self::$webGlobal['module'] = String::AddSlashesNew(trim(urldecode(self::$webServer['getstr'])), TRUE);
			}

			if (isset(self::$webRequest['c']))
			{
				self::$webGlobal['controller'] = self::$webRequest['c'];
				if (self::$webGlobal['module']!='' && self::$webGlobal['controller']!='')
				{
					self::$webGlobal['controller'] = self::$webGlobal['module'].'_Ctl_'.self::$webGlobal['controller'];
				}
			}

			if (isset(self::$webRequest['m']))
			{
				self::$webGlobal['method'] = self::$webRequest['m'];
			}
		}

		$tempPreLength = strlen(self::$webConfig['cookiePre']);
		foreach ($_COOKIE as $tempKey => $tempValue)
		{
			if (substr($tempKey, 0, $tempPreLength) == self::$webConfig['cookiePre'])
			{
				self::$webCookie[(substr($tempKey, $tempPreLength))] = String::AddSlashesNew($tempValue);
			}
		}

		if (!empty($_FILES))
		{
			self::$webUpfile = String::AddSlashesNew($_FILES);
		}

		unset($GLOBALS['_GET'], $GLOBALS['_POST'], $GLOBALS['_COOKIE'], $GLOBALS['_FILES'], $GLOBALS['HTTP_GET_VARS'], $GLOBALS['HTTP_POST_VARS'], $GLOBALS['HTTP_COOKIE_VARS'], $GLOBALS['HTTP_POST_FILES'], $GLOBALS['_REQUEST']);
	}

	/* 服务器参数处理 */
	private static function SetServer()
	{
		$webServer = array();
		$webServer['webhost'] = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
		$webServer['runfile'] = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
		$webServer['getstr'] = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ((isset($_SERVER['argv']) && !empty($_SERVER['argv'])) ? $_SERVER['argv'][0] : '');
		$webServer['geturl'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $webServer['runfile'].(!empty($webServer['getstr']) ? '?'.$webServer['getstr'] : '');
		if (!defined('WEB_HTMLFILE') || !WEB_HTMLFILE)
		{
			$webServer['geturl'] = str_replace('/index.php', '/', $webServer['geturl']);	//除掉默认的页面地址
		}
		$webServer['comeurl'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
		$webServer['pageurl'] = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS'])!='off') ? 'https://' : 'http://').$webServer['webhost'].$webServer['geturl'];

		//程序域名判断
		/*
		if (!preg_match('/^(([0-9a-z\-]+\.)?9518\.(cc|cn)|127\.0\.0\.1|localhost)$/i', $webServer['webhost']))
		{
			exit();
		}*/

		self::$webServer += $webServer;
	}

}	//end class

?>